package com.iking.housekeeping.controller.dept;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import com.iking.housekeeping.redis.RedisObjectService;
import com.iking.housekeeping.util.CodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.iking.housekeeping.common.CodeEnum;
import com.iking.housekeeping.common.ReturnCode;
import com.iking.housekeeping.entity.dept.SysDept;
import com.iking.housekeeping.entity.dtuser.DeptUser;
import com.iking.housekeeping.entity.user.SysUser;
import com.iking.housekeeping.httpbean.dept.reqbean.ReturnSysDept;
import com.iking.housekeeping.httpbean.dept.resbean.DeptDetail;
import com.iking.housekeeping.service.dept.DeptService;
import com.iking.housekeeping.service.dtuser.DeptUserService;
import com.iking.housekeeping.service.user.UserService;
import com.iking.housekeeping.util.UUIDUtil;

/**
 * 组织架构管理
 *
 * @author 秦甫杰,张重阳
 *
 */
@RestController
@RequestMapping("/dept")
public class DeptController {
	@Autowired
	private DeptService deptService;

	@Autowired
	private DeptUserService deptUserService;

	@Autowired
	private UserService userService;
	@Autowired
	private RedisObjectService<String> redisObjectService;
	/**
	 * 添加部门
	 *
	 * @param sysDept
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/addDept")
	public ReturnCode addDept(@RequestBody @Valid SysDept sysDept, BindingResult bindingResult) {
		// 判断参数是否合法
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			return new ReturnCode(CodeEnum.FAIL, msg, null);
		}
		// 通过部门名称查看部门
		SysDept sysDept1 = deptService.selectSysDeptByDName(sysDept.getfName());
		if (sysDept1 != null) {
			return new ReturnCode(CodeEnum.FAIL, "区域名称重复", null);
		}
		// 通过传入的父级部门的id查询自部门的集合
		List<SysDept> sysDeptlist = deptService.sysDeptList(sysDept.getfDeptPCode());
		// 如果子部门的集合的长度小于九
		sysDept.setfDeptCode(CodeUtil.getCodeByPCode(sysDept.getfDeptPCode(), sysDeptlist.size()));
		// 设置数据为未删除
		sysDept.setfIsDeleted(false);
		// 设置id
		sysDept.setfId(UUIDUtil.getUUID());
		// 添加部门
		deptService.addFatherDept(sysDept);
		return new ReturnCode(CodeEnum.SUCCESS);
	}

	/**
	 * 根据id删除部门
	 *
	 * @param fId
	 * @return
	 */
	@GetMapping(value = "/delDept/{fId}")
	public ReturnCode delDept(@PathVariable("fId") String fId) {
		// 首先根据id查询部门
		SysDept sysDept = deptService.selectDeptById(fId);
		// 根据查询到的部门code查询所有的部门，如果结果大于0，说明存在子部门，不能删除
		List<SysDept> deptChildren = deptService.sysDeptList(sysDept.getfDeptCode());
		if (deptChildren.size() > 0) {
			return new ReturnCode(CodeEnum.FAIL, "存在子部门，不能删除", null);
		}
		List<DeptUser> deptUser = deptUserService.selectbyDeptId(fId);
		if(deptUser.size() > 0){
			return new ReturnCode(CodeEnum.FAIL, "部门内有人员，不能删除", null);
		}
		sysDept.setfIsDeleted(true);
		deptService.deleteDeptById(fId);
		// 部门删除后重新排序
		List<SysDept> sortList = deptService.sysDeptList(sysDept.getfDeptPCode());
		//部门排序
		deptService.soltSysMenuList(sortList);
		return new ReturnCode(CodeEnum.SUCCESS);
	}
	/**
	 * 修改部门
	 */
	@PostMapping("/updateDept")
	public ReturnCode updateDept(@RequestBody SysDept sysDept, BindingResult bindingResult) {
		// 判断参数是否合法
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			return new ReturnCode(CodeEnum.FAIL, msg, null);
		}
		// 根据id查询部门
		SysDept thisDept = deptService.selectDeptById(sysDept.getfId());
		// 根据查询到的部门code查询所有的部门，如果结果大于0，说明存在子部门，不能删除
		List<SysDept> deptChildren = deptService.sysDeptList(sysDept.getfDeptCode());
		if (deptChildren.size() > 0) {
			return new ReturnCode(CodeEnum.FAIL, "存在子部门，不能修改", null);
		}
		List<DeptUser> deptUser = deptUserService.selectbyDeptId(sysDept.getfId());
		if(deptUser.size() > 0){
			return new ReturnCode(CodeEnum.FAIL, "部门内有人员，不能修改", null);
		}
		// 通过部门名称查看部门
		SysDept sysDept1 = deptService.selectSysDeptByDName(thisDept.getfName());
		if (sysDept1 != null && !sysDept1.getfId().equals(thisDept.getfId())) {
			return new ReturnCode(CodeEnum.FAIL, "区域名称重复", null);
		}
		if (sysDept.getfDeptPCode().equals(thisDept.getfDeptPCode())) {
			deptService.updateDept(sysDept);
		} else {
			// 根据要更改的父节点查询所有的子节点
			List<SysDept> deptList = deptService.sysDeptList(sysDept.getfDeptPCode());
			// 定义一个新添加的子节点
			String fDeptCode;
			// 如果子节点的长度大于0并且小于9
			fDeptCode = CodeUtil.getCodeByPCode(sysDept.getfDeptPCode(), deptList.size());
			// 更改子菜单的编号fDeptCode
			sysDept.setfDeptCode(fDeptCode);
			// 01
			// 更新当前子部门的编号
			deptService.updateDept(sysDept);
			// 获取当前
			List<SysDept> oldPChildren = deptService.sysDeptList(thisDept.getfDeptPCode());

			deptService.soltSysMenuList(oldPChildren);
		}
		return new ReturnCode(CodeEnum.SUCCESS, null);
	}

	/**
	 * 根据id查看部门
	 *
	 * @param fId
	 * @return
	 */
	@GetMapping(value = "/selectDeptById/{fId}")
	public ReturnCode selectDeptById(@PathVariable("fId") String fId) {
		if(fId == null || fId.trim().equals("")) {
			return new ReturnCode(CodeEnum.FAIL, null);
		}
		DeptDetail deptDetail = deptService.selectDeptDetailById(fId);
		if (deptDetail == null) {
			return new ReturnCode(CodeEnum.FAIL);
		}
		return new ReturnCode(CodeEnum.SUCCESS, deptDetail);
	}

	/**
	 * 根据两个id来更新
	 *
	 * @param fIdOne
	 * @param fIdTwo
	 * @return
	 */
	@GetMapping(value = "/changeDept/{fIdOne}/{fIdTwo}")
	public ReturnCode changeDept(@PathVariable("fIdOne") String fIdOne, @PathVariable("fIdOne") String fIdTwo) {
		//根据id查询所在的部门
		SysDept sysDept1 = deptService.selectDeptById(fIdOne);
		SysDept sysDept2 = deptService.selectDeptById(fIdOne);
		//截取部门code的前两位
		String fDeptCode1=sysDept1.getfDeptCode().substring(0, 2);
		String fDeptCode2=sysDept2.getfDeptCode().substring(0, 2);
		// 根据fcode的前两位进行模糊查询
		List<SysDept> deptList1 = deptService.selectListDeptByCode(fDeptCode1);
		List<SysDept> deptList2 = deptService.selectListDeptByCode(fDeptCode2);
		//定义当前的code
		String indexCode;
		//定义一个pCode
		String pCode;
		//遍历模糊查询的结果
		for (SysDept sysDept : deptList1) {
			indexCode = sysDept.getfDeptCode();
			pCode = sysDept.getfDeptPCode();
			//如果code的前两位不等于集合中的code
			if (!fDeptCode1.equals(sysDept.getfDeptCode())) {
				//设置父级code
				sysDept.setfDeptPCode(
						fDeptCode2 + pCode.substring(fDeptCode2.length(), pCode.length()));
				//设置code
				sysDept.setfDeptCode(fDeptCode2
						+ indexCode.substring(fDeptCode2.length(), indexCode.length()));
			} else {
				//如果相等只给code复制
				sysDept.setfDeptCode(fDeptCode2);
			}
			deptService.updateDept(sysDept);
		}
		/**
		 * 注释同上
		 */
		for (SysDept sysDept : deptList2) {
			indexCode = sysDept.getfDeptCode();
			pCode = sysDept.getfDeptPCode();
			if (!fDeptCode2.equals(sysDept.getfDeptCode())) {
				sysDept.setfDeptPCode(
						fDeptCode1 + pCode.substring(fDeptCode1.length(), pCode.length()));
				sysDept.setfDeptCode(fDeptCode1
						+ indexCode.substring(fDeptCode1.length(), indexCode.length()));
			} else {
				sysDept.setfDeptCode(fDeptCode1);
			}
			deptService.updateDept(sysDept);
		}
		return new ReturnCode(CodeEnum.SUCCESS);
	}

	/**
	 * 查看所有的部门
	 */
	@GetMapping(value = "/selectAllTree")
	public ReturnCode selectAllTree() {
		// 获取所有部门的列表
		List<ReturnSysDept> sysDeptList = deptService.selectAllSysDept();
		// 将部门列表转换为书结构
		sysDeptList = deptService.getDeptTree(sysDeptList, "");
		return new ReturnCode(CodeEnum.SUCCESS, sysDeptList);
	}

	@GetMapping(value = "/selectAll")
	public ReturnCode selectAll() {
		List<SysDept> listSysDept = deptService.selectAll();
		return new ReturnCode(CodeEnum.SUCCESS, listSysDept);
	}

	/**
	 * 根据部门id查询部门下的用户
	 * @param deptId
	 * @return
	 */
	@GetMapping(value = "/selectUserByDeptId/{deptId}")
	public ReturnCode selectUserByDeptId(@PathVariable("deptId") String deptId) {
		//判断出传入的部门ID是否为空
		if(deptId==null) {
			return new ReturnCode(CodeEnum.FAIL_EARROR_PARM);
		}
		//根据部门ID在关联表中查询部门下的所有用户id
		List<DeptUser> listDUser = deptUserService.selectbyDeptId(deptId);
		//判断该部门下是否有用户
		if(listDUser.size()==0) {
			return new ReturnCode(CodeEnum.SUCCESS, new ArrayList<SysUser>());
		}
		//定义一个list泛型集合接收当前所有的用户id
		List<String> listUserId=new ArrayList<String>();
		for (DeptUser deptUser : listDUser) {
			//把所有的用户id放入到ist泛型集合
			listUserId.add(deptUser.getfUserId());
		}
		//根据id查询所有的用户
        List<SysUser> userList = userService.selectSysUserByUserId(listUserId);
		return new ReturnCode(CodeEnum.SUCCESS, userList);
	}

	/**
	 * 删除某部门下的用户
	 * @param fUserId
	 * @param fDeptId
	 * @return
	 */
	@GetMapping(value="/delUser/{fUserId}/{fDeptId}")
	public ReturnCode delUser(@PathVariable("fUserId") String fUserId,@PathVariable("fDeptId") String fDeptId) {
		//判断传入的参数是否为空
		if(fUserId==null || fDeptId==null) {
			return new ReturnCode(CodeEnum.FAIL);
		}
		List<SysDept> menuList = deptService.selectAdminById(fUserId);
		List<SysDept> list = deptService.selectdepCod(fDeptId);
		// 判断当前登录人是否为管理员
		if ("".equals(menuList.get(0).getfDeptPCode()) || menuList.get(0).getfDeptPCode() == null) {
			return new ReturnCode(CodeEnum.FAIL,"该用户为管理员，不能被删除！",null);
	    }
	    else if (fUserId.equals(list.get(0).getfAdminUser())  ) {
			//判断当前登录人是否为区域管理员
			return new ReturnCode(CodeEnum.FAIL,"该用户为管理员，不能被删除！",null);
		}
		for (int i = 0; i < list.size(); i++) {
			String id=redisObjectService.get("webToken:" +list.get(i));
			if(id!=null){
				return new ReturnCode(CodeEnum.FAIL, "正在登录的用户不能删除！", null);
			}
		}
		//首先通过部门id查看所有的信息
		List<DeptUser> listDepts=deptUserService.selectbyDeptId(fDeptId);
		//判断该部门下是否有次用户ID
		for (DeptUser deptUser : listDepts) {
			if(!deptUser.getfUserId().equals(fUserId)) {
				return new ReturnCode(CodeEnum.FAIL);
			}else {
				//删除关联表
				deptUserService.delDeptUserByUserId(fUserId);
				//删除用户表
				userService.delUserById(fUserId);
			}
		}
		return new ReturnCode(CodeEnum.SUCCESS);
	}

	/**
	 * 在某部门下添加用户
	 * @param fDeptId
	 * @return
	 */
	@GetMapping(value="/addUserOnDept/{fDeptId}/{userName}/{password}")
	public ReturnCode addUserOnDept(@PathVariable("fDeptId") String fDeptId,
			@PathVariable("userName") String userName,@PathVariable("password") String password) {
		//判断传入的参数是否为空
		if(fDeptId==null || userName==null || password == null) {
			return new ReturnCode(CodeEnum.FAIL);
		}
		//查看是否有此部门
		if(deptUserService.selectbyDeptId(fDeptId).size()<0) {
			return new ReturnCode(CodeEnum.FAIL);
		}
		SysUser sysUser=new SysUser(UUIDUtil.getUUID(), userName,password);
		//添加用户
		userService.addSysUser(sysUser);
		return new ReturnCode(CodeEnum.SUCCESS);
 	}
}
